package com.jwong.common.context;

import com.jwong.common.util.InstanceUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PrimaryKeyContext {

    public static final String USER_PRIMARY_KEY = "user_primary_key";

    private PrimaryKeyContext() {}

    private static CommonContext<String, Long> CONTEXT_HOLDER =
            InstanceUtils.instance(ThreadLocalCommonContext.class, PrimaryKeyContext.class.getClassLoader());

    public static Long get() {
        Long userPrimaryKey = CONTEXT_HOLDER.get(USER_PRIMARY_KEY);
        if (log.isDebugEnabled()) {
            log.debug("get userPrimaryKey : {}", userPrimaryKey);
        }
        return userPrimaryKey;
    }

    public static void bind(Long userPrimaryKey) {
        if (log.isDebugEnabled()) {
            log.debug("bind userPrimaryKey : {}", userPrimaryKey);
        }
        CONTEXT_HOLDER.put(USER_PRIMARY_KEY, userPrimaryKey);
    }

    public static Long unbind() {
        Long userPrimaryKey = CONTEXT_HOLDER.remove(USER_PRIMARY_KEY);
        if (log.isDebugEnabled()) {
            log.debug("unbind userPrimaryKey : {} ", userPrimaryKey);
        }
        return userPrimaryKey;
    }
}
